package com.luckeys.controller;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.luckeys.contants.CommonContans;
import com.luckeys.ios.vo.IosUserVO;
import com.luckeys.service.UserService;
import com.luckeys.utils.SendMSGUtil;
import com.luckeys.vo.MessageVO;
import com.luckeys.vo.UserVO;

@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 1.登录接口
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/doLogin", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap doLogin(String userName, String password) {
		ModelMap resultMap = new ModelMap();
		if (StringUtils.isNotBlank(userName)
				&& StringUtils.isNotBlank(password)) {
			UserVO user = new UserVO();
			user.setUserName(userName);
			user.setPassword(password);
			user = userService.queryUser(user);
			if (null != user) {
				UserVO userVO = new UserVO();
				userVO.setUserUuid(user.getUserUuid());
				userVO.setLoginDate(new Date());
				userService.updateUser(userVO);
				String jsonUser = JSON.toJSONString(user).toString();
				IosUserVO josnUserVO = JSON.parseObject(jsonUser,
						IosUserVO.class);
				resultMap.put(CommonContans.STRUTS_BODY, josnUserVO);
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_SUCCESS);
			} else {
				resultMap.put(CommonContans.STRUTS_MESSAGE, "用户名或密码错误");
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_ERROR);
			}
		} else {
			resultMap.put(CommonContans.STRUTS_MESSAGE, "用户名或密码为空");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}
		return resultMap;
	}

	@RequestMapping(value = "/queryPage", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryUserPage(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();

		resultMap.put(CommonContans.STRUTS_DATA,
				userService.queryUserPage(user));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/addUser", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap addUser(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();
		user.setUserUuid(UUID.randomUUID().toString());
		resultMap.put(CommonContans.STRUTS_DATA, userService.addUser(user));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/deleteUser", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap deleteUser(String userUuid) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_DATA,
				userService.deleteUser(userUuid));
		resultMap
				.put(CommonContans.STRUTS_RESULT, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	@RequestMapping(value = "/queryUserById", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryUserById(String userUuid) {
		ModelMap resultMap = new ModelMap();
		UserVO user = userService.queryUserById(userUuid);
		resultMap.put(CommonContans.STRUTS_BODY, user);
		resultMap
				.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}
	
	@RequestMapping(value = "/queryIosUserById", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap queryIosUserById(String userUuid) {
		ModelMap resultMap = new ModelMap();
		IosUserVO user = userService.queryIosUserById(userUuid);
		resultMap.put(CommonContans.STRUTS_BODY, user);
		resultMap
		.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}

	/**
	 * 2.修改用户接口
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap updateUser(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();
		UserVO userVO = new UserVO();
		if (StringUtils.isNotBlank(user.getUserPhone())) {
			userVO.setUserPhone(user.getUserPhone());
			userVO = userService.queryUser(userVO);
		} else {
			userVO = null;
		}
		if (null != userVO) {
			resultMap.put(CommonContans.STRUTS_MESSAGE, "该手机号已经被注册过");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		} else {
			resultMap.put(CommonContans.STRUTS_MESSAGE,
					userService.updateUser(user));
			resultMap.put(CommonContans.STRUTS_CODE,
					CommonContans.STRUTS_SUCCESS);
		}
		return resultMap;
	}

	@RequestMapping(value = "/updateHead", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public ModelMap updateHead(UserVO user,
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request)
			throws Exception {
		ModelMap resultMap = new ModelMap();
		try {
			String file ="";
			for (MultipartFile myfile : myfiles) {
				if (myfile.isEmpty()) {
					
				} else {
					String realPath = request.getSession().getServletContext()
							.getRealPath("/image/user");
					String fileName = System.currentTimeMillis()
							+ "."
							+ StringUtils.lowerCase(myfile.getOriginalFilename()
									.split("\\.")[1]);
					file = "/image/user/" + fileName;
					if("1".equals(user.getUserHead()))
					{
						user.setUserHead(file);
					}
					if("1".equals(user.getBackImage()))
					{
						user.setBackImage(file);
					}
					FileUtils.copyInputStreamToFile(myfile.getInputStream(),
							new File(realPath, fileName));
				}
			}
			userService.updateUser(user);
			resultMap.put(CommonContans.STRUTS_BODY,user);
			resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		} catch (Exception e) {
			resultMap.put(CommonContans.STRUTS_MESSAGE,"修改头像失败");
			resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}
		return resultMap;
	}

	/**
	 * 3.注册用户接口
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/registeredUser", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap registeredUser(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();
		// 1.判断验证码有效性
		if (StringUtils.isNotBlank(user.getUserPhone())
				&& StringUtils.isNotBlank(user.getCodes())) {
			UserVO checkUser = userService.checkCodes(user);
			if (null == checkUser) {
				resultMap.put(CommonContans.STRUTS_MESSAGE, "验证码已失效或输入错误");
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_ERROR);
			} else {
				// 2.判断手机号是否被注册过
				UserVO userVO = new UserVO();
				userVO.setUserPhone(user.getUserPhone());
				userVO = userService.queryUser(userVO);
				if (null != userVO) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, "该手机号已经被注册过");
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
				} else {
					// 3.添加用户
					String userUuid = UUID.randomUUID().toString();
					user.setUserUuid(userUuid);
					user.setIsSend("1");
					user.setUserType("1");
					user.setUserName(user.getUserPhone());
					int result = userService.addUser(user);
					if (result == 1) {
						user.setPassword(null);
						String jsonUser = JSON.toJSON(user).toString();
						IosUserVO josnUserVO = JSON.parseObject(jsonUser,
								IosUserVO.class);
						resultMap.put(CommonContans.STRUTS_BODY, josnUserVO);
						resultMap.put(CommonContans.STRUTS_CODE,
								CommonContans.STRUTS_SUCCESS);
					} else {
						resultMap.put(CommonContans.STRUTS_MESSAGE, "注册失败");
						resultMap.put(CommonContans.STRUTS_CODE,
								CommonContans.STRUTS_ERROR);
					}
				}
			}
		} else {
			resultMap.put(CommonContans.STRUTS_MESSAGE, "用户名，验证码为空");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}

		return resultMap;
	}

	/**
	 * 4.密码重置接口
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/resetPassword", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap resetPassword(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();
		// 1.判断验证码有效性
		if (StringUtils.isNotBlank(user.getUserPhone())
				&& StringUtils.isNotBlank(user.getCodes())) {
			UserVO checkUser = userService.checkCodes(user);
			if (null == checkUser) {
				resultMap.put(CommonContans.STRUTS_MESSAGE, "验证码已失效或输入错误");
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_ERROR);
			} else {
				// 2.判断手机号是否被注册过
				UserVO userVO = new UserVO();
				userVO.setUserPhone(user.getUserPhone());
				userVO = userService.queryUser(userVO);
				if (null == userVO) {
					resultMap.put(CommonContans.STRUTS_MESSAGE, "当前用户不存在");
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
				} else {
					// 3.修改用户
					user.setUserUuid(userVO.getUserUuid());
					int result = userService.updateUser(user);
					if (result == 1) {
						resultMap.put(CommonContans.STRUTS_MESSAGE, "密码重置成功");
						resultMap.put(CommonContans.STRUTS_CODE,
								CommonContans.STRUTS_SUCCESS);
					} else {
						resultMap.put(CommonContans.STRUTS_MESSAGE, "注册失败");
						resultMap.put(CommonContans.STRUTS_CODE,
								CommonContans.STRUTS_ERROR);
					}
				}
			}
		} else {
			resultMap.put(CommonContans.STRUTS_MESSAGE, "用户名，验证码为空");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}

		return resultMap;
	}

	/**
	 * 5.注册发送短信
	 * 
	 * @param userPhone
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/registered", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap registered(String userPhone, String password) {
		ModelMap resultMap = new ModelMap();
		// 1.判断手机号是否为空
		if (StringUtils.isBlank(userPhone)) {
			resultMap.put(CommonContans.STRUTS_MESSAGE,
					"userPhone is empty....");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		}
		// 2.判断手机号是否被注册过
		UserVO user = new UserVO();
		user.setUserPhone(userPhone);
		user = userService.queryUser(user);
		if (null != user && StringUtils.isBlank(password)) {
			resultMap.put(CommonContans.STRUTS_MESSAGE, "该手机号已经被注册过");
			resultMap
					.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_ERROR);
		} else {
			// 3.发送短信验证码
			String context = "您的短信注册码为:{1}，有效期为5分钟，过期请重新获取";
			double code = Math.random();
			code = code * 9000 + 1000;
			String codes = String.valueOf((int) code);
			context = context.replace("{1}", String.valueOf((int) code));
			try {
				String result = SendMSGUtil.sendMSG(null, null, userPhone,
						context);
				if ("1".equals(result)) {
					MessageVO message = new MessageVO();
					message.setUserPhone(userPhone);
					message.setCodes(codes);
					// 获取5分钟之后的时间插入数据库
					long currentTime = System.currentTimeMillis();
					currentTime += 5 * 60 * 1000;
					Date date = new Date(currentTime);
					message.setExpirationTime(date);
					userService.addMessage(message);
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_SUCCESS);
				} else {
					resultMap.put(CommonContans.STRUTS_MESSAGE, "短信发送失败，请稍后重试");
					resultMap.put(CommonContans.STRUTS_CODE,
							CommonContans.STRUTS_ERROR);
				}
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put(CommonContans.STRUTS_MESSAGE, e.getMessage());
				resultMap.put(CommonContans.STRUTS_CODE,
						CommonContans.STRUTS_ERROR);
			}
		}
		return resultMap;
	}

	@RequestMapping(value = "/addDeviceToken", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap addDeviceToken(@RequestBody UserVO user) {
		ModelMap resultMap = new ModelMap();
		resultMap.put(CommonContans.STRUTS_MESSAGE,
				userService.updateUser(user));
		resultMap.put(CommonContans.STRUTS_CODE, CommonContans.STRUTS_SUCCESS);
		return resultMap;
	}
}
